﻿using MediatR;
using SmartCity.Passport.API.Application.Commands;
using SmartCity.Passport.API.DTO;
using SmartCity.Passport.API.ErrorCode;
using SmartCity.Passport.API.Extensions;
using SmartCity.Passport.Domain.Entites;
using SmartCity.Passport.ErrorCode;
using SmartCity.Passport.Infrastructure.Interfaces;

namespace SmartCity.Passport.API.Application.CommandHandlers
{
    /// <summary>
    /// 部门查询命令处理
    /// </summary>
    public class DepartmentCommandHandler:IRequestHandler<DepartmentCommand,ApiResult<List<DepartmentDto>>>
    {
        private readonly IBaseRepository<Department> departmentRep;

        public DepartmentCommandHandler(IBaseRepository<Department> departmentRep)
        {
            this.departmentRep = departmentRep;
        }

        public Task<ApiResult<List<DepartmentDto>>> Handle(DepartmentCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<DepartmentDto>> result = new ApiResult<List<DepartmentDto>>();
            result.code = ApiEnum.SearchSuccess;
            result.message = ApiEnum.SearchSuccess.GetDescription();

            List<DepartmentDto> list = new List<DepartmentDto>();
            var allList = departmentRep.GetAll().ToList();
            var topList = allList.Where(x => x.ParentId == 0);
            foreach (var item in allList)
            {
                DepartmentDto dto = new DepartmentDto();
                dto.value = item.DepartmentId;
                dto.label = item.DepartmentName;
                list.Add(dto);
                Setcascader(allList, dto);
            }
            result.data = list;
            return Task.FromResult(result);
        }
        public void Setcascader(List<Department> allList,DepartmentDto parent)
        {
            var list = allList.Where(x => x.ParentId == parent.value);
            foreach (var item in list)
            {
                DepartmentDto dto = new DepartmentDto();
                dto.value = item.DepartmentId;
                dto.label = item.DepartmentName;
                parent.children.Add(dto);
                Setcascader(allList,dto);
            }
        }
    }
}
